<template>
  <Card>
    <Button type="primary" class="trademark-btn" @click="showSaveOrUpdateTrademarkModal">
      <template #icon><PlusOutlined /> </template>
      添加品牌
    </Button>
    <!-- 
      dataSource 表格数据
      columns 列
      pagination 分页器
      rowKey 遍历元素key找什么属性
      bordered 边框
     -->
    <Table
      :dataSource="trademarkList"
      :columns="columns"
      :pagination="{
        pageSizeOptions: ['3', '6', '9', '12'],
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total) => `总共 ${total} 条`,
        current: currentPage,
        pageSize,
        total,
        onChange: getTrademarkList,
        onShowSizeChange: getTrademarkList,
      }"
      :loading="tableLoading"
      rowKey="id"
      bordered
    >
      <template #index="{ index }">
        {{ index + 1 }}
      </template>
      <!-- 
        record 遍历行数据
        text 当前logoUrl数据
        index 下标
        record table列信息
       -->
      <template #logoUrl="{ record }">
        <img :src="record.logoUrl" :alt="record.tmName" class="trademark-img" />
      </template>

      <template #operator="{ record }">
        <Button type="primary" @click="showSaveOrUpdateTrademarkModal(record)">修改</Button>
        <Button
          type="primary"
          danger
          class="trademark-danger-btn"
          @click="showRemoveTrademarkModal(record)"
        >
          删除
        </Button>
      </template>
    </Table>

    <Modal v-model:visible="visible" title="添加品牌" @ok="submitForm">
      <Form
        ref="form"
        :model="trademark"
        :rules="rules"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 14 }"
        class="trademark-form"
      >
        <FormItem label="品牌名称" name="tmName">
          <Input v-model:value="trademark.tmName" placeholder="请输入品牌名称" />
        </FormItem>
        <FormItem label="品牌LOGO" name="logoUrl">
          <Upload
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="`${apiUrl}/admin/product/fileUpload`"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="trademark.logoUrl" :src="trademark.logoUrl" alt="avatar" />
            <div v-else>
              <loading-outlined v-if="uploadLoading" />
              <plus-outlined v-else />
              <div class="ant-upload-text">上传品牌LOGO</div>
            </div>
          </Upload>
          <span>只能上传jpg/png文件，且不超过500kb</span>
        </FormItem>
      </Form>
    </Modal>
  </Card>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted, createVNode } from 'vue';
  import {
    Card,
    Button,
    Table,
    Modal,
    Form,
    FormItem,
    Input,
    Upload,
    message,
  } from 'ant-design-vue';
  import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import {
    getTrademarkListApi,
    saveTrademarkApi,
    updateTrademarkApi,
    removeTrademarkApi,
  } from '/@/api/product/trademark';
  import { trademarkListModel, TrademarkItem } from '/@/api/product/model/trademarkModel';
  import { useGlobSetting } from '/@/hooks/setting';
  import { FileItem, FileInfo } from '../form';

  // 获取请求地址前缀（参考axios的baseURL获取方式）
  const apiUrl = useGlobSetting().apiUrl;
  // 表单规则不需要响应式
  const rules = {
    tmName: [{ required: true, message: '请输入品牌名称', trigger: 'blur' }],
    logoUrl: [{ required: true, message: '请上传品牌LOGO' }],
  };
  // 定义响应式数据
  // 表格数据
  const trademarkList = ref<trademarkListModel>([
    // { id: 1, tmName: '111', logoUrl: '11111' },
    // { id: 2, tmName: '222', logoUrl: '22222' },
    // { id: 3, tmName: '333', logoUrl: '33333' },
  ]);
  // 列
  const columns = [
    {
      // 表格列标题
      title: '序号',
      // 遍历元素key属性
      key: '1',
      // 宽度
      width: 70,
      // 居中
      align: 'center',
      slots: {
        // 插槽的名称
        customRender: 'index',
      },
    },
    {
      title: '品牌名称',
      // 渲染dataSource中哪个属性
      dataIndex: 'tmName',
      key: '2',
    },
    {
      title: '品牌logo',
      dataIndex: 'logoUrl',
      key: '3',
      slots: {
        // 插槽的名称
        customRender: 'logoUrl',
      },
    },
    {
      title: '操作',
      key: '4',
      slots: {
        // 插槽的名称
        customRender: 'operator',
      },
    },
  ];
  // 当前页码
  const currentPage = ref(1);
  // 每页条数
  const pageSize = ref(3);
  // 总数
  const total = ref(0);
  // loading
  const tableLoading = ref(false);
  const uploadLoading = ref(false);
  const visible = ref(false);
  // 表单项数据
  const trademark = reactive<TrademarkItem>({
    id: 0,
    tmName: '',
    logoUrl: '',
  });
  // 表单实例对象
  const form = ref();

  // 获取品牌列表函数：为了复用
  const getTrademarkList = async (page: number, limit: number) => {
    tableLoading.value = true;
    currentPage.value = page;
    pageSize.value = limit;
    const res = await getTrademarkListApi(page, limit);
    tableLoading.value = false;
    currentPage.value = page;
    pageSize.value = limit;
    trademarkList.value = res.records;
    message.success('获取品牌分页成功');
    total.value = res.total;
  };

  // 提交表单
  const submitForm = () => {
    // 校验表单
    form.value.validate().then(async () => {
      // 表单验证通过
      const isUpdate = !!trademark.id;

      if (isUpdate) {
        await updateTrademarkApi(trademark);
      } else {
        await saveTrademarkApi(trademark.tmName, trademark.logoUrl);
      }
      message.success(`${isUpdate ? '更新' : '添加'}品牌成功`);
      visible.value = false;
      getTrademarkList(currentPage.value, pageSize.value);
    });
    // 不想报错就写
    // .catch((err) => {});
  };

  // 上传图片时触发
  const handleChange = (info: FileInfo) => {
    // 上传中，调为loading
    if (info.file.status === 'uploading') {
      uploadLoading.value = true;
      return;
    }
    // 上传成功，更新数据
    if (info.file.status === 'done') {
      trademark.logoUrl = info.file.response.data;
      uploadLoading.value = false;
      return;
    }
    // 上传失败，提示错误
    if (info.file.status === 'error') {
      uploadLoading.value = false;
      message.error('上传图片失败');
    }
  };

  // 上传图片之前触发
  const beforeUpload = (file: FileItem) => {
    // 对上传图片的类型和大小进行限制
    const fileTypes = ['image/jpeg', 'image/jpg', 'image/png'];

    const isValidFileType = fileTypes.includes(file.type);
    const isValidFileSize = file.size / 1024 < 500;

    if (!isValidFileType) {
      message.error('上传头像图片只能是 JPG 或 PNG 格式!');
    }
    if (!isValidFileSize) {
      message.error('上传头像图片大小不能超过 500KB!');
    }

    // 返回值true，通过，可以上传图片
    // 返回值false，不通过，不会上传图片
    return isValidFileType && isValidFileSize;
  };

  // 显示对话框Modal
  const showSaveOrUpdateTrademarkModal = (
    tm: TrademarkItem = { id: 0, tmName: '', logoUrl: '' },
  ) => {
    // 清空表单的校验结果
    // 第一次不要
    form.value?.clearValidate();
    trademark.id = tm.id;
    trademark.tmName = tm.tmName;
    trademark.logoUrl = tm.logoUrl;
    visible.value = true;
  };

  // 显示删除对话框
  const showRemoveTrademarkModal = (tm: TrademarkItem) => {
    Modal.confirm({
      title: () => '警告',
      icon: () => createVNode(ExclamationCircleOutlined),
      content: () => `您确认要删除 ${tm.tmName} 品牌吗？`,
      okText: () => '确认',
      cancelText: () => '取消',
      onOk: async () => {
        await removeTrademarkApi(tm.id as number);
        message.success('删除品牌成功');
        getTrademarkList(currentPage.value, pageSize.value);
      },
    });
  };

  // mounted生命周期
  onMounted(() => {
    getTrademarkList(currentPage.value, pageSize.value);
  });
</script>

<style lang="less" scoped>
  .trademark-btn {
    margin-bottom: 15px;
  }

  .trademark-danger-btn {
    margin-left: 10px;
  }

  .trademark-img {
    width: 200px;
    height: 100px;
  }

  .trademark-form {
    margin: 20px 0 0 20px;
  }
</style>
